<template>
  <div>
    <!-- 菜单modal弹窗 -->
    <dtDialog
      :title="modalTitle"
      :visible.sync="dialogVisible"
      :lock-scroll="false"
      :append-to-body="true"
      :is-loading="loading"
      @closeDialog="onModalClosed"
      @comfirmBtn="onSubmit()"
    >
      <el-form ref="addMenuFormRef" slot="content" label-width="104px"
               :model="addMenuForm" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model.trim="addMenuForm.menuName" maxlength="10" placeholder="请输入菜单名称"
                        show-word-limit class="limit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="action == 'edit'">
          <el-col :span="24">
            <el-form-item label="菜单编号" prop="menuCode" label-width="104px">
              <el-input v-model.trim="addMenuForm.menuCode" maxlength="50" placeholder="请输入菜单编号"
                        show-word-limit class="limit" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio v-model="addMenuForm.menuType" :label="'1'">目录</el-radio>
              <el-radio v-model="addMenuForm.menuType" :label="'2'">菜单</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="父级菜单" prop="pname">
              <el-dialog
                :visible.sync="insideDialogVisible"
                :close-on-click-modal="false"
                append-to-body
                width="800px"
                title="父级菜单"
              >
                <!-- 搜索栏 -->
                <el-input
                  v-model.trim="filterText"
                  prefix-icon="el-icon-search"
                  placeholder="输入搜索组织名称"
                  maxlength="30"
                  style="margin: 20px 0;"
                />
                <el-tree
                  :ref="menuTree.ref"
                  :props="menuTree.props"
                  :data="menuTree.data"
                  node-key="nodeId"
                  :filter-node-method="filterNode"
                  check-strictly
                  highlight-current
                  :default-expanded-keys="menuTree.defaultExpandedKeys"
                />
                <span slot="footer" class="dialog-footer">
                  <el-button type="primary" @click="onSaveParentMenu">保存</el-button>
                  <el-button @click="insideDialogVisible = false">关闭</el-button>
                </span>
              </el-dialog>
              <el-input v-model.trim="addMenuForm.pname" readonly placeholder="请选择父级菜单"
                        @focus="onFocusMenuPath" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model.trim="addMenuForm.sort" placeholder="请输入排序" :oninput="initPositiveInteger()"
                        maxlength="8" show-word-limit class="limit" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </dtDialog>
  </div>
</template>
<script>
// import { getSysMenuTree, addSysMenu, getSysMenuDetail, editSysMenu } from '@/framework/api/menu'
import { isExternal, positiveInteger } from '@/framework/utils/validate'
import { pick } from 'lodash'
import { upperCamelCase } from '@/framework/utils/index'
import { getMenuTree, add, edit, getDetail } from '@/api/classroom/directoryManage'

export default {
  name: 'LearnMenuModal',
  data() {
    return {
      loading: false,
      buttonLoading: false,
      action: '',
      dialogVisible: false,
      insideDialogVisible: false,
      filterText: '',
      addMenuForm: {
        menuName: '',
        menuCode: '',
        pname: '',
        sort: '',
        menuType: '1',
        pid: ''
      },
      visibleBoolean: true,
      menuTree: {
        ref: 'tree',
        props: {
          label: 'title',
          children: 'children'
        },
        data: [],
        defaultExpandedKeys: ['-1']
      },
      iconOption: {
        FontAwesome: false,
        ElementUI: true,
        eIcon: false,
        eIconSymbol: false,
        addIconList: [],
        removeIconList: []
      },
      rules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'change' }
        ],
        menuCode: [
          { required: true, message: '请输入菜单编号', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'change' }
        ],
        menuType: [
          { required: true, message: '请选择菜单类型', trigger: 'change' }
        ],
        pname: [
          { required: true, message: '请选择父级菜单', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    tenantId() {
      return this.$store.state.user.tenantId
    },
    modalTitle() {
      let title = ''
      if (this.action === 'add') {
        title = '新增菜单'
      } else if (this.action === 'edit') {
        title = '修改菜单'
      }
      return title
    }
  },

  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getMenuList()
  },
  methods: {
    getMenuList() {
      getMenuTree().then((resp) => {
        this.menuTree.data = [...resp.data]
      })
    },
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    add() {
      this.edit({})
    },
    edit(record) {
      if (this.action !== 'add' && this.action !== '') {
        const { menuName, menuCode, sort, menuType, pid } = record
        this.addMenuForm = {
          menuName,
          menuCode,
          pname: '',
          sort,
          menuType,
          pid
        }
        getDetail(record.id).then((resp) => {
          this.addMenuForm = Object.assign({}, pick(resp.data,
            'id', 'menuName', 'menuCode', 'pid', 'pname', 'sort', 'menuType'))
        })
      } else {
        // this.handleMenuType('M')
      }
      this.dialogVisible = true
    },
    // 点击菜单路径
    onFocusMenuPath() {
      this.insideDialogVisible = true
      this.filterText = ''
      // getSysMenuTree({ appCode: this.addMenuForm.appCode }).then((resp) => {
      //   this.menuTree.data = [...resp.data]
      // })
    },
    // 点击保存父菜单
    onSaveParentMenu() {
      const treeNode = this.$refs.tree.getCurrentNode()
      if (treeNode != null) {
        this.addMenuForm.pname = treeNode.title
        this.addMenuForm.pid = treeNode.id
      }
      // this.addMenuForm.menuParentId = treeNode.id
      // this.handleMenuType(this.addMenuForm.menuType)
      this.insideDialogVisible = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    // 点击提交
    onSubmit() {
      // 校验表单
      this.$refs.addMenuFormRef.validate((result, message) => {
        // 校验通过
        if (result) {
          this.loading = true
          if (this.buttonLoading) {
            return
          }
          // todo 初始化name
          this.addMenuForm.menuCode = upperCamelCase(this.addMenuForm.menuCode)
          if (this.action === 'add') {
            // 提交按钮显示加载中，无法重复点击
            this.buttonLoading = true

            // 发送请求，新增菜单
            add(this.addMenuForm).then((resp) => {
              const type = resp.success ? 'success' : 'error'
              // 提示消息
              this.$message({
                type,
                message: '新增成功'
              })
              // 添加成功，自动关闭菜单添加对话框
              if (resp.success) {
                this.dialogVisible = false
                this.getMenuList()
                this.$emit('added')
              } else {
                this.buttonLoading = false
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
              this.buttonLoading = false
            })
          } else if (this.action === 'edit') {
            this.buttonLoading = true
            edit(this.addMenuForm).then((resp) => {
              const type = resp.success ? 'success' : 'error'
              // 提示消息
              this.$message({
                type,
                message: '修改成功'
              })
              // 添加成功，自动关闭菜单添加对话框
              if (resp.success) {
                this.dialogVisible = false
                this.getMenuList()
                this.$emit('edited')
              } else {
                this.buttonLoading = false
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
              // 启用提交按钮
              this.buttonLoading = false
            })
          }
        }
      })
    },
    initModal() {
      this.$refs.addMenuFormRef.resetFields()
      this.addMenuForm = {
        menuName: '',
        menuCode: '',
        pname: '',
        sort: '',
        menuType: '1',
        pid: ''
      }
    },
    onModalClosed() {
      this.initModal()
      this.buttonLoading = false
    },
    handleSelectedIcon(icon) {
      this.addMenuForm.antdvIcon = icon
      if (this.addMenuForm.appIcon) {
        this.$refs.addMenuFormRef.clearValidate('antdvIcon')
      } else {
        this.$refs.addMenuFormRef.validateField('antdvIcon')
      }
    }
  }
}
</script>

<style lang="scss">
  .add-menu-dialog .el-dialog__body {
    padding-top: 0px;
    height: 500px;
    overflow-y: auto;
  }
  .add-menu-dialog .el-dialog {
    margin-top: 5vh !important;
  }
</style>
<style lang="scss" scoped>
   .item {
      margin: 4px;
    }
    .tips{
      color: red;
      padding-left:50px ;

    }
  .icon_class {
    // color: red;
   ::v-deep .el-form-item__content{
      display: flex;
      .el-icon-delete{
        line-height: 36px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
</style>
